

package com.mystudy.quartzspringbootdemo.job;


import com.mystudy.quartzspringbootdemo.entity.QuartzEntity;
import com.mystudy.quartzspringbootdemo.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;


/**
 * description:定时任务执行类
 * @author Thanks
 * @expection
 * @return
 */
@Slf4j
public class ScheduleJob extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        QuartzEntity scheduleJob = (QuartzEntity) context.getMergedJobDataMap()
                .get(QuartzEntity.JOB_PARAM_KEY);

        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            log.info("任务准备执行，任务ID：" + scheduleJob.getJobId());
            //获取java类对象
            Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
            //获取执行方法
            Method method = target.getClass().getDeclaredMethod("run", String.class);
            method.setAccessible(true);
            //执行
            method.invoke(target, scheduleJob.getParams());
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.info("任务执行完毕，任务ID：" + scheduleJob.getJobId() + "  总共耗时：" + times + "毫秒");
        } catch (Exception e) {
            log.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);
        }
    }
}
